package com.example.yrdev.ordering_system.homeOptions;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.yrdev.ordering_system.Activity.ShoppingCartActivity;
import com.example.yrdev.ordering_system.Adapter.GoodAdapter;
import com.example.yrdev.ordering_system.Adapter.GoodTypeAdapter;
import com.example.yrdev.ordering_system.Common.CommonActivity;
import com.example.yrdev.ordering_system.Dialog.ShoppingCartDialog;
import com.example.yrdev.ordering_system.Model.Good;
import com.example.yrdev.ordering_system.Model.GoodType;
import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class CommodityActivity extends CommonActivity {

    @InjectView(R.id.typeList)ListView typeList;
    @InjectView(R.id.item_detailList)ListView itemDetailList;//商品列表
    @InjectView(R.id.search_txt)
    EditText search_txt;
    @InjectView(R.id.contentContainer)LinearLayout contentContainer;
    @InjectView(R.id.noItem)
    LinearLayout noItem;

    GoodTypeAdapter typeAdapter;
    GoodAdapter goodAdapter;
    private  int currentPos=0;
     private   ShoppingCartDialog shoppingCart;
     private ArrayList<Good> arrayList;//商品数组
     private String currentKind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.commodity_purchase_layout);

        setBarTitle("商品消费");
        showBackButton();

        ButterKnife.inject(this);
       initView();




    }


    Good correspondGood;//想买的商品
    public void initView(){
        showRightButtonWithListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();

                intent.setClassName("com.telpo.tps550.api", "com.telpo.tps550.api.barcode.Capture");

                try {
                    startActivityForResult(intent, 0x124);

                } catch (ActivityNotFoundException e) {

                    // Toast.makeText(MainActivity.this, getResources().getString(R.string.identify_fail), Toast.LENGTH_LONG).show();
                }


            }
        },"扫描");

         arrayList=Good.getItemDetailList(this);
          shoppingCart=new ShoppingCartDialog(this);

        shoppingCart.setShopCartListener(new ShoppingCartDialog.shopCartListener() {
            @Override
            public void pay(ArrayList<Good> shoppingList) {
                Intent intent=new Intent();
                GlobalFunction.printTextByTag("shopsize"+shoppingList.size()+"");

                intent.putExtra("shopbag",shoppingList);
               // gotoActivityWithIntent(intent,PaymentActivity.class,0);

//                gotoActivity(PaymentActivity.class,0);

            }
        });
        typeAdapter=new GoodTypeAdapter(this);

        typeAdapter.setGoodTypeArrayList(GoodType.getTypeList(this));
        typeList.setAdapter(typeAdapter);

        goodAdapter=new GoodAdapter(this);
        goodAdapter.setGoodArrayList(arrayList);
        itemDetailList.setAdapter(goodAdapter);
        currentKind=typeAdapter.getGoodTypeArrayList().get(0).getId();
        filterGoodBaseOnType(currentKind);

        search_txt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            filterGood(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        typeList.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                try {
                    if (typeList.getChildCount()>0){

                        typeList.getChildAt(currentPos).setSelected(true);

                    }


                }catch (Exception e){

                    GlobalFunction.printTextByTag("error");

                }


            }
        });
        typeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               currentPos=position;

                selectView(position);
            }
        });
        search_txt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_DONE){

                    hideKeyboard();





                }
                return false;
            }
        });
        search_txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_txt.setCursorVisible(true);
            }
        });


        itemDetailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//商品列表

                correspondGood=goodAdapter.getGoodArrayList().get(position);


                if (Integer.valueOf(correspondGood.getStoredNumber())>0){

                    showDialog();

                }else {

                   GlobalFunction.ToastAlert(CommodityActivity.this,"暂时没货");
                }


            }
        });
    }
    public void showShoppingCart(View v){
        if (shoppingCart.getShoppingList().size()==0){
            GlobalFunction.ToastAlert(this,"您还没购物任何东西");
            return;

        }


        //GlobalFunction.printTextByTag(shoppingCart.getShoppingList()+"");
    //    shoppingCart.show();
       Intent intent=new Intent();
        intent.putExtra("shopList",shoppingCart.getShoppingList());
        gotoActivityWithIntent(intent,ShoppingCartActivity.class,0);

//    gotoActivity(ShoppingCartActivity.class,0);


    }
    private  Good  assignFromCorrespondGood(){//从想购物的商品进行复制

        Good temp=new Good(correspondGood.getId(),correspondGood.getName(),correspondGood.getPinyinID());
        temp.setPriceOut(correspondGood.getPriceOut());
        temp.setPurchaseCount(purchaseAmount);
        temp.setStoredNumber(correspondGood.getStoredNumber());
        temp.setPriceIn(correspondGood.getPriceIn());
        temp.setDisoountable(correspondGood.getDisoountable());

        return temp;

    }

    Integer purchaseAmount=1;

    private   void showDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        LayoutInflater inflater=this.getLayoutInflater();
        View respView=inflater.inflate(R.layout.commodity_ask_amount_layout, null);
        // EditText editText=respView.findViewById()
        final EditText amount=(EditText)respView.findViewById(R.id.amount);
     //   amount.setOnTouchListener(editTextOnTouchListener());
        builder.setView(respView).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

               purchaseAmount= Integer.valueOf(amount.getText().toString());

                if ( purchaseAmount> Integer.valueOf(correspondGood.getStoredNumber())){

                    GlobalFunction.ToastAlert(CommodityActivity.this,"暂时只剩"+correspondGood.getStoredNumber()+"个"+correspondGood.getName());

                }else {
                    shoppingCart.addNewShoppingGood(assignFromCorrespondGood());
                    showShoppingCart(null);


                }



//                selected_goods.setAmount(Integer.valueOf(amount.getText().toString()));
//                checkSelectedItem();

            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        reloadTB();


        if (requestCode == 0x124) {

            if (resultCode == 0) {

                if (data != null) {

                    String qrcode = data.getStringExtra("qrCode");

                    GlobalFunction.ToastAlert(this,"Scan result:" + qrcode);


                }
            }

        }


        if (resultCode==RESULT_FIRST_USER){
            ArrayList<Good> shoppingList=(ArrayList<Good>)data.getSerializableExtra("shopList");
            if (shoppingList!=null){

                shoppingCart.setShoppingList(shoppingList);
            }
        }

        if (resultCode==RESULT_OK)
            shoppingCart.clearShoppinglist();





    }
private  void reloadTB(){
    arrayList=Good.getItemDetailList(this);
    filterGoodBaseOnType(currentKind);

    typeAdapter.setGoodTypeArrayList(GoodType.getTypeList(this));
    typeAdapter.notifyDataSetChanged();
}
    private void hideKeyboard(){
        search_txt.setCursorVisible(false);
//        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(search_txt.getWindowToken(),
//                InputMethodManager.RESULT_UNCHANGED_SHOWN);

    }
    public void filterGood(String string){

        try {
            ArrayList<Good> temp=new ArrayList<>();

            ArrayList<Good> filtered=filterGoodBaseOnType(currentKind);
            if (goodAdapter!=null && goodAdapter.getGoodArrayList().size()>0){//当前分类有对应商品
                for (Good good :filtered){


                    if (good.getName().equals(string)||good.getPinyinID().contains(string)||good.getId().contains(string) && ( good.getKind().equals(currentKind)))
                        temp.add(good);

                }
            }

            if (temp.size()>0)
            goodAdapter.setGoodArrayList(temp);
            else {
                GlobalFunction.printTextByTag("cc");
            }
        }catch (Exception e){

          GlobalFunction.printTextByTag(e.getMessage());

        }


    }

    private void selectView(int pos){
        try {
            for (int i = 0; i <typeList.getChildCount() ; i++) {
                View view=typeList.getChildAt(i);
                view.setSelected(false);
            }

            View view=typeList.getChildAt(pos);
            view.setSelected(true);

            currentKind=typeAdapter.getGoodTypeArrayList().get(pos).getId();
            filterGoodBaseOnType(currentKind);

//            arrayList.clear();
//            goodAdapter.notifyDataSetChanged();

            //getItemDetail( typeAdapter.getGoodTypeArrayList().get(pos).getId());

        }catch (Exception e){

            GlobalFunction.printTextByTag("error");

        }





    }
    private ArrayList<Good> filterGoodBaseOnType(String type){
        ArrayList<Good> temp=new ArrayList<>();
        for (Good good:arrayList){
            if (good.getKind().equals(type)){
                temp.add(good);

            }
        }

        if (temp.size()==0){

            noItem.setVisibility(View.VISIBLE);
            contentContainer.setVisibility(View.GONE);

        }else {

            noItem.setVisibility(View.GONE);
            contentContainer.setVisibility(View.VISIBLE);
            goodAdapter.setGoodArrayList(temp);
        }


return temp;

    }






}
